<?php

namespace App\Http\Controllers;

use App\Exceptions\InvalidRequestException;
use App\Models\Product;
use Illuminate\Http\Request;

class ProductsController extends Controller
{
    public function index(Request $request)
    {
        $products = Product::where('on_sale',true)
            ->when($request->has('search'), function ($query){
                $like = '%'.request('search').'%';
                // 模糊搜索商品标题、商品详情、SKU 标题、SKU描述
                $query->where(function ($query) use ($like) {
                    $query->where('title', 'like', $like)
                        ->orWhere('description', 'like', $like)
                        ->orWhereHas('skus', function ($query) use ($like) {
                            $query->where('title', 'like', $like)
                                ->orWhere('description', 'like', $like);
                        });
                });
            })
            ->when($request->has('order'), function ($query){
                if (preg_match('/^(.+)_(asc|desc)$/', request('order'), $m)) {
                    // 如果字符串的开头是这 3 个字符串之一，说明是一个合法的排序值
                    if (in_array($m[1], ['price', 'sold_count', 'rating'])) {
                        // 根据传入的排序值来构造排序参数
                        $query->orderBy($m[1], $m[2]);
                    }
                }
            })->paginate(16);
        return view('products.index',[
            'products' => $products,
            'filters'  => [
                'search' => request('search'),
                'order'  => request('order'),
            ],
        ]);
    }
    public function show(Request $request,Product $product)
    {
        if(!$product->on_sale){
            return InvalidRequestException('商品暂未上架');
        }
        $favored = false;
        if($user = $request->user()){
            // 从当前用户已收藏的商品中搜索 id 为当前商品 id 的商品
            // boolval() 函数用于把值转为布尔值
            $favored = boolval($user->favoriteProducts()->find($product->id));
        }
        return view('products.show',[
            'product' => $product,
            'favored' => $favored
        ]);
//        return response()->json(['code' => 1,'data' => array_except($product->toArray(), ['created_at', 'updated_at'])]);
    }
    public function favor(Product $product, Request $request)
    {
        $user = $request->user();
        if ($user->favoriteProducts()->find($product->id)) {
            return [];
        }

        $user->favoriteProducts()->attach($product);

        return [];
    }
    public function disfavor(Product $product, Request $request)
    {
        $user = $request->user();
        $user->favoriteProducts()->detach($product);

        return [];
    }
}
